package com.sj.hh.ui.blackbox.record;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.rong.mbt.personal.activity.PermissionsActivity;
import com.rong.mbt.personal.activity.PermissionsChecker;
import com.sj.hh.R;
import com.sj.hh.picker.GlideImageLoader;
import com.sj.hh.ui.blackbox.event.VideoFilePathEvent;
import com.sj.hh.util.OkHttp3Util;
import com.sj.hh.util.SelectValueUtil;
import com.sj.hh.video.activity.VideoRecordActivity;
import com.sj.hh.video.utils.PermissionChecker;
import com.sj.hh.video.utils.ToastUtils;
import com.sj.hh.video.view.MediaController;
import com.socks.library.KLog;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.rongcloud.im.server.entity.PickerType;
import cn.rongcloud.im.server.response.BaseResponse;
import cn.rongcloud.im.server.response.RecordFileResponse;
import cn.rongcloud.im.server.utils.json.JsonMananger;
import cn.rongcloud.im.ui.activity.base.BaseActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 添加文件记录
 */
public class AddFileRecordActivity extends BaseActivity {

    private static final int FILE_LIST_BY_PAGE = 1;

    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.ll_type)
    LinearLayout llType;
    @BindView(R.id.tv_file_type)
    TextView tvFileType;
    @BindView(R.id.ll_file_type)
    LinearLayout llFileType;
    @BindView(R.id.tv_is_default_show)
    TextView tvIsDefaultShow;
    @BindView(R.id.ll_is_default_show)
    LinearLayout llIsDefaultShow;
    @BindView(R.id.edit_remark)
    EditText editRemark;
    @BindView(R.id.p_info_regisetphone)
    TextView pInfoRegisetphone;
    @BindView(R.id.btn_select_img)
    Button btnSelectImg;

    private static final int REQUEST_PERMISSION = 4;  //权限请求
    @BindView(R.id.video)
    PLVideoTextureView video;
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    static final String[] PERMISSIONS = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    private boolean isClickCamera;

    private int pageNum = 1;
    private String type;
    private String fileType;
    private String isDefaultShow;
    private GalleryConfig galleryConfig;
    private List<String> path = new ArrayList<>();
    private RecordFileResponse.DataBean recordFileResponse;
    private String id;
    private String videoFilePath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_file_record);
        ButterKnife.bind(this);
        setTitle("添加文件记录");

        EventBus.getDefault().register(this);

        initView();
        initData();

    }

    private void initView() {
        Button rightButton = getHeadRightButton();
        rightButton.setVisibility(View.GONE);
        mHeadRightText.setVisibility(View.VISIBLE);
        mHeadRightText.setText(R.string.de_save);
        mHeadRightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("10013".equals(type)) {
                    ArrayList<String> videoPath = new ArrayList<>();
                    if (!TextUtils.isEmpty(videoFilePath))
                        videoPath.add(videoFilePath);
                    updateImageFile(videoPath);
                }else {
                    updateImageFile(path);
                }
            }
        });


        mPermissionsChecker = new PermissionsChecker(this);

        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.sj.hh.FileProvider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 9)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .maxSize(9)                             // 配置多选时 的多选数量。    默认：9
                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(true)                     // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build();

        video.setLooping(true);
        video.setAVOptions(new AVOptions());
        MediaController mediaController = new MediaController(this, true, false);
        mediaController.setOnClickSpeedAdjustListener(mOnClickSpeedAdjustListener);
        video.setMediaController(mediaController);
    }

    private void updateImageFile(List<String> path) {
        String remark = editRemark.getText().toString().trim();

        String[] uploadTaskPaths = new String[path.size()];
        for (int i = 0; i < path.size(); i++) {
            uploadTaskPaths[i] = path.get(i);
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("type", type);
        map.put("ft", "3");
        map.put("df", isDefaultShow);
//        map.put("imgpath",uploadTaskPaths[0]);
        map.put("remark", remark);
        map.put("id", id);
        OkHttp3Util.uploadFile(this, OkHttp3Util.uploadFileRecordUrl, uploadTaskPaths, null, map, new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String json = response.body().string();
                    //{"msg":"上传成功","resultCode":0}
                    BaseResponse baseResponse = JsonMananger.jsonToBean(json, BaseResponse.class);
                    KLog.e("---", "onResponse: " + json);

                    if (baseResponse.getResultCode() == 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(mContext, "保存成功!!", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    finish();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initData() {
        recordFileResponse = (RecordFileResponse.DataBean) getIntent().getSerializableExtra("RecordFileResponse");
        if (recordFileResponse != null) {
            type = recordFileResponse.getType() + "";
            tvType.setText(SelectValueUtil.getInstance().getMatching(SelectValueUtil.getInstance().type, type));
            id = recordFileResponse.getId() + "";
            pInfoRegisetphone.setText(recordFileResponse.getImgpath());
            editRemark.setText(recordFileResponse.getRemark());
            tvIsDefaultShow.setText(SelectValueUtil.getInstance().getMatching(SelectValueUtil.getInstance().isTure, recordFileResponse.getDt() + ""));
            if ("10013".equals(type)) {
                video.setVisibility(View.VISIBLE);
            }else {
                video.setVisibility(View.GONE);
            }
        }

    }

    @OnClick({R.id.ll_type, R.id.ll_file_type, R.id.ll_is_default_show, R.id.btn_select_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_type:
                final ArrayList<PickerType> pickerData = SelectValueUtil.getInstance().getPickerData(SelectValueUtil.getInstance().type);
                showPickerView(pickerData, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        tvType.setText(pickerData.get(options1).getValue());
                        type = pickerData.get(options1).getId();
                    }
                });
                break;
            case R.id.ll_file_type:
                final ArrayList<PickerType> fileTypes = SelectValueUtil.getInstance().getPickerData(SelectValueUtil.getInstance().fileType);
                showPickerView(fileTypes, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        tvFileType.setText(fileTypes.get(options1).getValue());
                        fileType = fileTypes.get(options1).getId();
                    }
                });
                break;
            case R.id.ll_is_default_show:
                final ArrayList<PickerType> isDefaultShows = SelectValueUtil.getInstance().getPickerData(SelectValueUtil.getInstance().isTure);
                showPickerView(isDefaultShows, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        tvIsDefaultShow.setText(isDefaultShows.get(options1).getValue());
                        isDefaultShow = isDefaultShows.get(options1).getId();
                    }
                });
                break;
            case R.id.btn_select_img:
                if ("10013".equals(type)) {
                    if (isPermissionOK()) {
                        jumpToCaptureActivity();
                    }
                } else {
                    photoDialog();
                }
                break;
        }
    }

    public void jumpToCaptureActivity() {
        Intent intent = new Intent(this, VideoRecordActivity.class);
        intent.putExtra(VideoRecordActivity.PREVIEW_SIZE_RATIO, "4:3");
        intent.putExtra(VideoRecordActivity.PREVIEW_SIZE_LEVEL, "720P");
        intent.putExtra(VideoRecordActivity.ENCODING_MODE, "HW");
        intent.putExtra(VideoRecordActivity.ENCODING_SIZE_LEVEL, "480x480");
        intent.putExtra(VideoRecordActivity.ENCODING_BITRATE_LEVEL, "1000Kbps");
        intent.putExtra(VideoRecordActivity.AUDIO_CHANNEL_NUM, "单声道");
        startActivity(intent);
    }

    private boolean isPermissionOK() {
        PermissionChecker checker = new PermissionChecker(this);
        boolean isPermissionOK = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checker.checkPermission();
        if (!isPermissionOK) {
            ToastUtils.s(this, "Some permissions is not approved !");
        }
        return isPermissionOK;
    }

    @Subscribe
    public void onEvent(VideoFilePathEvent event) {
        if (event != null) {
            videoFilePath = event.getVideoFilePath();
            if (!TextUtils.isEmpty(videoFilePath)){
                video.setVisibility(View.VISIBLE);
                playVideo(videoFilePath);
            }
        }
    }

    private void playVideo(String videoFilePath) {
        video.setVideoPath(videoFilePath);
    }

    private MediaController.OnClickSpeedAdjustListener mOnClickSpeedAdjustListener = new MediaController.OnClickSpeedAdjustListener() {
        @Override
        public void onClickNormal() {
            // 0x0001/0x0001 = 2
            video.setPlaySpeed(0X00010001);
        }

        @Override
        public void onClickFaster() {
            // 0x0002/0x0001 = 2
            video.setPlaySpeed(0X00020001);
        }

        @Override
        public void onClickSlower() {
            // 0x0001/0x0002 = 0.5
            video.setPlaySpeed(0X00010002);
        }
    };

    private IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {

        @Override
        public void onStart() {
        }

        @Override
        public void onSuccess(List<String> photoList) {
            path = photoList;
            if (photoList != null && photoList.size() == 1) {
                pInfoRegisetphone.setText(photoList.get(0));
            }
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onFinish() {

        }

        @Override
        public void onError() {

        }
    };

    private Dialog dialog_photo;

    @SuppressLint("NewApi")
    private void photoDialog() {
        dialog_photo = new Dialog(this, com.rong.mbt.personal.R.style.photo_dialog);
        View view = LayoutInflater.from(this).inflate(com.rong.mbt.personal.R.layout.dialog_take_photo, null);
        dialog_photo.setContentView(view);
        Window window = dialog_photo.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(com.rong.mbt.personal.R.style.bottomDialogStyle);
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        if (!dialog_photo.isShowing()) {
            dialog_photo.show();
        }
        view.findViewById(com.rong.mbt.personal.R.id.tv_open_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_photo.dismiss();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                        startPermissionsActivity();
                    } else {
                        openCamera();
                    }
                } else {
                    openCamera();
                }
                isClickCamera = true;
            }
        });
        view.findViewById(com.rong.mbt.personal.R.id.tv_choose_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_photo.dismiss();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                        startPermissionsActivity();
                    } else {
                        openCamera();
                    }
                } else {
                    openCamera();
                }
                isClickCamera = false;
            }
        });
        view.findViewById(com.rong.mbt.personal.R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog_photo.isShowing()) {
                    dialog_photo.hide();
                }
            }
        });
    }

    private void openCamera() {
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(this);
    }

    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(this, REQUEST_PERMISSION,
                PERMISSIONS);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (video != null)
            video.stopPlayback();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (video != null)
            video.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (video != null)
            video.start();
    }

}
